package org.hbhk.hxl.gateway.filter;

import org.hbhk.hxl.gateway.filter.breaker.BreakerManager;
import org.hbhk.hxl.gateway.model.Circuitbreaker;
import org.hbhk.hxl.gateway.services.ServiceUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.NettyWriteResponseFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Mono;

/**
 * 
 * 服务的熔断处理
 *
 */
@Component
public class CircuitbreakerIntercptor implements GlobalFilter, Ordered {

	@Override
	public int getOrder() {
		return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER - 7;
	}

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		String url = exchange.getRequiredAttribute(GatewayFilter.GATEWAY_REQUEST_ROUTE_URL);

		Circuitbreaker breaker = ServiceUtil.getBreaker(url);
		if (breaker == null) {
			return chain.filter(exchange);
		}
		BreakerManager manager = BreakerManager.getBreakerManager(url);
		// 判断是否熔断
		if (manager == null) {
			return chain.filter(exchange);
		}
		manager.protectedCodeIsAboutToBeCalled();
		Mono<Void> mono = chain.filter(exchange);
		return mono;

	}

}